<?php

namespace App\Http\Controllers;

use App\Sundry;
use App\Services\OSS;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SundryController extends Controller
{
    /**
     * 搜索分类
     *
     * @param  Request
     * @return Response
     */
    public function category(Request $request)
    {
        try{
            $data['name'] = $request->input('name', '');
            if(!empty($data['name'])){
                $list = DB::table('base_category')->where('name', 'like', '%'.$data['name'].'%')->get();
            }else{
                $list = DB::table('base_category')->get();
            }
            return response()->json(['success'=>true,'code'=>1000,'message'=>$list]);
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }

    /**
     * 搜索地址
     *
     * @param  Request
     * @return Response
     */
    public function address(Request $request)
    {
        try{
            $data['name'] = $request->input('name', '');
            $isShop = $request->input('isShop', '0');
            $list = [];
            if(!empty($data['name'])){
                $country = DB::table('base_country')->where('name', 'like', '%'.$data['name'].'%')->get();
                $province = DB::table('base_province')->where('name', 'like', '%'.$data['name'].'%')->get();
                $city = DB::table('base_city')->where('name', 'like', '%'.$data['name'].'%')->get();
                $area = DB::table('base_area')->where('name', 'like', '%'.$data['name'].'%')->get();
                if(!empty($country[0])){
                    foreach($country as $k=>$v){
                        array_push($list,[
                            'country'=>$v,
                            'num'=>DB::table('goods')->where('country_id','=',$v->id)->count()
                        ]);
                        if(DB::table('base_province')->where('pid','=',$v->id)->count() > 0){
                            $baseProvince = DB::table('base_province')->where('pid','=',$v->id)->get();
                            foreach($baseProvince as $kk=>$vv){
                                array_push($list,[
                                    'country'=>$v,
                                    'province'=>$vv,
                                    'num'=>DB::table('goods')->where([['country_id','=',$v->id],['province_id','=',$vv->code]])->count()
                                ]);
                            }
                        }
                    }
                }
                if(!empty($province[0])){
                    foreach($province as $k=>$v){
                        $pinfo = DB::table('base_country')->where('id','=',$v->pid)->first();
                        array_push($list,[
                            'country'=>$pinfo,
                            'province'=>$v,
                            'num'=>DB::table('goods')->where([
                                ['country_id','=',$pinfo->id],
                                ['province_id','=',$v->code]
                            ])->count()
                        ]);
                        if(DB::table('base_city')->where('pcode','=',$v->code)->count() > 0){
                            $baseCity = DB::table('base_city')->where('pcode','=',$v->code)->get();
                            foreach($baseCity as $kk=>$vv){
                                array_push($list,[
                                    'country'=>$pinfo,
                                    'province'=>$v,
                                    'city'=>$vv,
                                    'num'=>DB::table('goods')->where([
                                        ['country_id','=',$pinfo->id],
                                        ['province_id','=',$v->code],
                                        ['city_id','=',$vv->code]
                                    ])->count()
                                ]);
                            }
                        }
                    }
                }
                if(!empty($city[0])){
                    foreach($city as $k=>$v){
                        $cinfo = DB::table('base_province')->where('code','=',$v->pcode)->first();
                        $ccinfo = DB::table('base_country')->where('id','=',$cinfo->pid)->first();
                        array_push($list,[
                            'province'=>$cinfo,
                            'country'=>$ccinfo,
                            'city'=>$v,
                            'num'=>DB::table('goods')->where([
                                ['country_id','=',$ccinfo->id],
                                ['province_id','=',$cinfo->code],
                                ['city_id','=',$v->code]
                            ])->count()
                        ]);
                        if(DB::table('base_area')->where('pcode','=',$v->code)->count() > 0){
                            $baseArea = DB::table('base_area')->where('pcode','=',$v->code)->get();
                            foreach($baseArea as $kk=>$vv){
                                array_push($list,[
                                    'province'=>$cinfo,
                                    'country'=>$ccinfo,
                                    'city'=>$v,
                                    'area'=>$vv,
                                    'num'=>DB::table('goods')->where([
                                        ['country_id','=',$ccinfo->id],
                                        ['province_id','=',$cinfo->code],
                                        ['city_id','=',$v->code],
                                        ['area_id','=',$vv->code]
                                    ])->count()
                                ]);
                            }
                        }
                    }
                }
                if(!empty($area[0])){
                    foreach($area as $k=>$v){
                        $ainfo = DB::table('base_city')->where('code','=',$v->pcode)->first();
                        $aainfo = DB::table('base_province')->where('code','=',$ainfo->pcode)->first();
                        $aaainfo = DB::table('base_country')->where('id','=',$aainfo->pid)->first();
                        array_push($list,[
                            'country'=>$aaainfo,
                            'province'=>$aainfo,
                            'city'=>$ainfo,
                            'area'=>$v,
                            'num'=>DB::table('goods')->where([
                                ['country_id','=',$aaainfo->id],
                                ['province_id','=',$aainfo->code],
                                ['city_id','=',$ainfo->code],
                                ['area_id','=',$v->code]
                            ])->count()
                        ]);
                    }
                }
                //根据地区按照所属数量排序
                if(!empty($list[0])){
                    $arr = array_column($list,'num');
                    array_multisort($arr,SORT_DESC,$list );
                }
//                print_r($list);exit;
            }else{
                //按照最近1月找货信息发布区域数量倒叙
                $time = time()-30*24*60*60;
                $res = DB::table('goods')->where([['is_del','=','2'],['search_goods','<>','0'],['create_time','>',$time]])->groupBy('search_goods')->orderByRaw('count(search_goods) desc')->limit(10)->get();
                if(!empty($res[0])){
                    foreach($res as $k=>$v){
                        $arr = array();
                        $country = DB::table('base_country')->where('id','=',$v->country_id)->first();
                        $province = DB::table('base_province')->where('code','=',$v->province_id)->first();
                        $city = DB::table('base_city')->where('code','=',$v->city_id)->first();
                        $area = DB::table('base_area')->where('code','=',$v->area_id)->first();
                        if($country){
                            $arr['country'] = $country;
                        }
                        if($province){
                            $arr['province'] = $province;
                        }
                        if($city){
                            $arr['city'] = $city;
                        }
                        if($area){
                            $arr['area'] = $area;
                        }
                        $list[]  = $arr;
                    }
                }
            }
            return response()->json(['success'=>true,'code'=>1000,'message'=>$list]);
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }


    /**
     * 图片上传
     *
     * @param  Request
     * @return Response
     */
    public function upload(Request $request)
    {
        try{
            $userId = $request->input('userId', '');
            if(empty($userId)){
                return response()->json(['success'=>false,'code'=>6001,'message'=>'必填参数不能为空']);
            }
            //获取上传的文件
            $file = $request->file('file');
            //获取上传图片的临时地址
            $tmppath = $file->getRealPath();
            //生成文件名
            $fileName = str_random(5) . $file->getFilename() . time() .date('ymd') . '.' . $file->getClientOriginalExtension();
            //拼接上传的文件夹路径(按照日期格式1810/17/xxxx.jpg)
            $pathName = date('Y-m/d').'/'.$fileName;
            //上传图片到阿里云OSS
            OSS::publicUpload('doitforyou', $pathName, $tmppath, ['ContentType' => $file->getClientMimeType()]);
            //获取上传图片的Url链接
            $Url = OSS::getPublicObjectURL('doitforyou', $pathName);
            // 返回状态给前端，Laravel框架会将数组转成JSON格式
            return response()->json(['success'=>true,'code'=>1000,'message'=>$Url]);
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }


    /**
     * 微信解密
     *
     * @param  Request
     * @return Response
     */
    public function decrypt(Request $request)
    {
        try{
            $userId = $request->input('userId', '');
            $encryptedData = $request->input('encryptedData', '');
            $iv = $request->input('iv', '');
            if(empty($userId) || empty($encryptedData) || empty($iv)){
                return response()->json(['success'=>false,'code'=>6002,'message'=>'必填参数不能为空']);
            }
            //查询sessionkey
            $sessionkey = DB::table('login_token')->where('users_id','=',$userId)->value('session_key');
            if(!$sessionkey){
                return response()->json(['success'=>false,'code'=>6003,'message'=>'sessionkey无效']);
            }
            $appId = env('APP_ID');
            $list = self::decryptData($sessionkey,$appId,$encryptedData,$iv,$data);
            if($list === 0){
                $list = json_decode($data);
            }
            return response()->json(['success'=>true,'code'=>1000,'message'=>$list]);
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }


    /**
     * 查询oss图片格式
     *
     * @param  Request
     * @return Response
     */
    public function picStyle()
    {
        try{
            $res = DB::table('oss_format')->first();
            return response()->json(['success'=>true,'code'=>1000,'message'=>$res]);
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }

    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function decryptData($sessionKey,$appid,$encryptedData, $iv, &$data )
    {
        if (strlen($sessionKey) != 24) {
            return -41001;
        }
        $aesKey=base64_decode($sessionKey);


        if (strlen($iv) != 24) {
            return -41002;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            return -41003;
        }
        if( $dataObj->watermark->appid != $appid )
        {
            return -41003;
        }
        $data = $result;
        return 0;
    }


    /**
     * 存储用户formId
     *
     * @param  Request
     * @return Response
     */
    public function addFormId(Request $request)
    {
        try{
            $userId = $request->input('userId', '');
            $formId = $request->input('formId', '');
            if(empty($userId) || empty($formId)){
                return response()->json(['success'=>false,'code'=>6003,'message'=>'必填参数不能为空']);
            }
            $data['users_id'] = $userId;
            $data['form_id'] = $formId;
            $data['date'] = date("Y-m-d");
            $data['time'] = time();
            $res = DB::table('users_formid')->insert($data);
            if($res){
                return response()->json(['success'=>true,'code'=>1000,'message'=>'添加成功']);
            }else{
                return response()->json(['success'=>false,'code'=>6004,'message'=>'添加失败']);
            }
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }
}
